package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalAuthFilter implements GlobalFilter, Ordered {
    private AntPathMatcher matcher = new AntPathMatcher();
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、如果路径规则不匹配格式： /api/**/auth/**   直接放行
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if(!matcher.match("/api/**/auth/**" , path)){
            //放行请求
            return chain.filter(exchange);
        }
        // 2、如果匹配 获取请求头中的token进行校验  获取失败 直接拒绝请求
        String token = request.getHeaders().getFirst("token");
        boolean hasKey = false;
        if(StringUtils.hasLength(token)){
            // 3、如果token获取到  再根据token到redis中判断是否存在对应的数据 如果存在放行
            String userInfoKey = "user:login:"+ token;
            hasKey = stringRedisTemplate.hasKey(userInfoKey);
        }
        //如果hasKey为true 放行请求： 携带有效token的请求 可以访问 auth路径
        if(hasKey){
            return chain.filter(exchange);
        }
        //如果hasKey为false：表示 没有携带token 或者token失效
        //响应一个200的报文，响应体的Result code值设置为208
        ServerHttpResponse response = exchange.getResponse();
        //响应报文状态码
        response.setStatusCode(HttpStatus.OK);
        //响应报文头
        response.getHeaders().add("content-type" ,
                MediaType.APPLICATION_JSON_UTF8_VALUE);
        //准备写入到响应体中的数据： 创建了result对象 转为json字符串的 字节数组
        Result<Object> result = Result.build(ResultCodeEnum.LOGIN_EXPIRE_ERROR, null);
        byte[] bs = JSON.toJSONString(result).getBytes();
        //将json字节数组写入到响应体中 并返回结果
        DataBuffer data = response.bufferFactory().wrap(bs);
        return response.writeWith(Mono.just(data));

    }

    @Override
    public int getOrder() {
        return -1;
    }
}
